package com.mmall.controller;

import com.mmall.pojo.SysUser;
import com.mmall.service.ISysUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author wangtengyu
 * @Create 2018-03-12-10:03
 */
@Controller
public class UserController {

    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/login.page")
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        SysUser sysUser = iSysUserService.findBykeyword(username);

        String errorMsg = "";
        String ret = request.getParameter("ret");

        if (StringUtils.isBlank(username)) {
            errorMsg = "用户名不能为空";
        } else if (StringUtils.isBlank(password)) {
            errorMsg = "密码不能为空";
        } else if (sysUser == null) {
            errorMsg="查询不到指定用户";
        }else if(!StringUtils.equals(sysUser.getPassword(), MD5Util.MD5Encode(password,"utf-8"))){
            errorMsg="用户名和密码不一致";
        }else if(sysUser.getStatus()!=1){
            errorMsg="用户已被冻结";
        }else {
            //登录成功
            request.getSession().setAttribute("user",sysUser);
            if(StringUtils.isNotBlank(ret)){
                response.sendRedirect(ret);
            }
            response.sendRedirect("/admin/index.page");
        }

        //登录失败
        request.setAttribute("error", errorMsg);
        request.setAttribute("username", username);
        if (StringUtils.isNotBlank(ret)) {
            request.setAttribute("ret", ret);
        }
        String path = "signin.jsp";
        request.getRequestDispatcher(path).forward(request, response);
    }

    /**
     * 登出
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/logout.page")
    public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        String path="signin.jsp";
        response.sendRedirect(path);
    }




}
